<template>
  <a-result :status="loginStatus" :title="loginMessage" />
</template>
<script lang="ts" setup>
import { localStorage } from '@/utils/local-storage';
import { useUserStore, RESET_CURRENT_USER, TENANT_ID } from '@/store/user';
import { SSO_TYPE } from '@/store/app';
import { loginByTenant } from '@/api/avic/system/SingleSignOnApi';
import { setExpireTime, setCookie, removeCookie } from '@/utils/common-util';
const { proxy } = getCurrentInstance();
const redirectUrl = 'redirect_url';
const userStore = useUserStore();
const loginStatus = ref('info');
const loginMessage = ref('正在登录应用系统，请稍候...');

onBeforeMount(() => {
  tenantLogin();
});
function routerPush(parms) {
  nextTick(() => {
    proxy.$router.push(parms);
  });
}

function showResult({ success, message = '' }) {
  loginStatus.value = success ? 'success' : 'warning';
  loginMessage.value = message || (success ? '登录成功' : '登录失败');
}
async function tenantLogin() {
  // 清除token
  userStore[RESET_CURRENT_USER]();
  // 清除租户信息
  removeCookie(TENANT_ID);
  // 记单点登录类型
  localStorage.set(SSO_TYPE, 'httpheaderLogin');

  try {
    // 本地存储租户信息
    if (proxy.$route.query.tenantId) {
      setCookie(TENANT_ID, proxy.$route.query.tenantId);
    } else {
      removeCookie(TENANT_ID);
      throw new Error(`租户数据缺失:${TENANT_ID}`);
    }
    const param = { ...proxy.$route.query };
    delete param.tenantId;
    delete param[redirectUrl];
    if (Object.keys(param).length) {
      const response = await loginByTenant(param);
      // const response = await httpheaderLoginRequest(`${paramName}=${param}`);
      const { code, data, errorDesc, message } = response;
      if (code === '200') {
        showResult({ success: true });
        userStore.SET_TOKEN(data.token, data.refreshToken);
        setExpireTime(data.expireTime);
        const loginUser = data.userInfo;
        const { consoleType } = loginUser;

        // 重定向优先级 redirectUrl > 后台用户
        if (proxy.$route.query[redirectUrl]) {
          let redirect = proxy.$route.query[redirectUrl];
          redirect = typeof redirect === 'string' ? redirect : redirect[0];
          window.name = 'portal';
          proxy.$router.push(decodeURIComponent(redirect));
        } else {
          // 单点登录成功后如果没有配置redirectUrl则需要根据用户类型判断是否跳转后台管理
          if (consoleType === '0' && proxy.$settings.consoleUrl) {
            let { consoleUrl } = proxy.$settings;
            consoleUrl = consoleUrl.endsWith('/') ? consoleUrl : `${consoleUrl}/`;
            window.name = 'console';
            window.open(`${consoleUrl}access-from-portal?access_token=${data.token}&redirect_url=/backstage`, 'console');
          } else {
            window.name = 'portal';
            routerPush('/');
          }
        }
      } else {
        showResult({ success: false, message: errorDesc || message });
      }
    } else {
      throw new Error('认证信息缺失');
    }
  } catch (error) {
    console.error(error);
    showResult({ success: false, message: error.message });
  }
}
</script>
